
package net.bblot.lottery.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Window;
import android.webkit.WebView;

import com.umeng.socialize.UMShareAPI;

import net.bblot.lottery.PackegeConfig;

import com.marsscp.cp.R;

import net.bblot.lottery.util.AdsPopwindowUtil;
import net.bblot.lottery.util.AppConfig;
import net.bblot.lottery.util.AppUtil;
import net.bblot.lottery.util.FileUtil;
import net.bblot.lottery.util.Logger;
import net.bblot.lottery.util.ToastUtill;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;


public class MainActivity extends BaseDroidGapActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        init();
        // init_splash();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

        this.appView.getView().setBackgroundResource(R.drawable.screen);// 设置背景图片
        String hash = "";
        String data = getIntent().getDataString();
        if (!TextUtils.isEmpty(data)) {
            hash = data.replace("cptoback://", "");
        }
        final String hash2 = hash;
        //加载主页面
        if (AppManager.isIndexPageReady()) {
            loadUrl(getIndexPath(hash));
        }
//        addShortcut();
        showSplashScreen(5000, new onSplashScreenCloseListener() {
            @Override
            public void onClose(boolean refresh) {
                Logger.e(TAG, "onClose");
                if (refresh) {
                    appView.clearCache();
                    appView.clearHistory();
                    loadUrl(getIndexPath(hash2));
                }
            }
        });
        AdsPopwindowUtil.requestAdsInfo(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                AdsPopwindowUtil.showAdsPopWindow(MainActivity.this);
                //UmengTool.checkWxBySelf(MainActivity.this);//检查微信后台配置的包名和签名
//				WebInterface webInterface = new WebInterface(MainActivity.this);
//                Logger.e(TAG, "代理id=" + webInterface.getStationId());
//                Logger.e(TAG, "渠道id=" + webInterface.getUmengChannel());
//                Logger.e(TAG, "aeskey" + webInterface.getAesKey());
//                Logger.e(TAG, "aeskIv" + webInterface.getAesIv());
//                Log.e(TAG,"IMEI:" + AppUtil.getImei(getApplicationContext()));
//                Log.e(TAG, AppConfig.getAppMetaData(getApplication(), "STATION_ID"));
            }
        }, 1500);
    }

    private String getIndexPath(String hash) {
        String indexPage = "";
        List<File> list = FileUtil.searchFile(AppConfig.getWebRootDir(this), PackegeConfig.INDEX_PAGE);
        if (list.size() > 0) {
            String path = list.get(0).getAbsolutePath();
            indexPage = "file:///" + path;
        } else {
            indexPage = "file:///android_asset/www/android.html";
        }
        if (!TextUtils.isEmpty(hash)) {
            indexPage += hash;
        }
        Logger.e(TAG, "indexpage:" + indexPage);
        return indexPage;

    }

    @Override
    public void onUrlJumpWechat(String url) {
        super.onUrlJumpWechat(url);
        Intent i1 = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        i1.setAction(Intent.ACTION_VIEW);
        startActivity(i1);
    }

    @Override
    public void onUrlJumpAliPay(String url) {
        if (AppUtil.hasInstall(this, "com.eg.android.AlipayGphone")) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);
        }
    }

    @Override
    public void onUrlJumpCustom(String url) {
        super.onUrlJumpCustom(url);
        Logger.e(TAG, "onUrlJumpCustom:" + url);
        String hash = "";
        hash = url.replace("cptoback://", "");
        if (!TextUtils.isEmpty(hash)) {
            if (hash.endsWith("/")) {
                hash = hash.substring(0, hash.length() - 1);
            }
            loadUrl(getIndexPath(hash), false);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub

        super.onNewIntent(intent);
        String oldData = "" + this.appView.getUrl();
        setIntent(intent);
        String data = getIntent().getDataString();
        if (data != null && !oldData.equals(data)) {
            String hash = "";
            hash = data.replace("cptoback://", "");
            if (!TextUtils.isEmpty(hash)) {
                loadUrl(getIndexPath(hash));
            }
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }


    private void addShortcut() {
        Intent addShortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        // 不允许重复创建
        addShortcutIntent.putExtra("duplicate", false);// 经测试不是根据快捷方式的名字判断重复的
        String app_name = getResources().getString(R.string.app_name);
        // 名字
        addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, app_name);
        // 图标
        addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                Intent.ShortcutIconResource.fromContext(MainActivity.this, R.drawable.ic_launcher));
        // 设置关联程序
        Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
        launcherIntent.setClass(MainActivity.this, MainActivity.class);
        launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);
        // 发送广播
        sendBroadcast(addShortcutIntent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);//完成回调
    }

    private static class MyHandler extends Handler {
        WeakReference<MainActivity> mActity;

        public MyHandler(MainActivity activity) {
            this.mActity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mActity.get().setIsExit(false);
        }
    }

    private boolean isExit = false;

    public void setIsExit(boolean isExit) {
        this.isExit = isExit;
    }

//	@Override
//	public void onBackPressed() {
//        Log.e(TAG, "onBackPressed");
//		if (this.appView.canGoBack()) {
//            this.appView.backHistory();
//        } else {
//
//            exit();
//        }
//	}

    private MyHandler mHandler = new MyHandler(this);
    private AppManager appManager = AppManager.getAppManager();

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastUtill.showShortToast(this, "再按一次退出");
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            super.onBackPressed();
            appManager.AppExit(this);
        }
    }
}
